import { assetManager } from "cc";
import { tyqSDK } from "../Managers/TyqSDK";

class TyqResManager {
    private static _instance: TyqResManager;
    private constructor() {
    }
    public static get instance(): TyqResManager {
        if (this._instance == null) {
            this._instance = new TyqResManager();
        }

        return this._instance;
    }

    /**
     * 从bundle中加载某个资源，优先使用缓存中的
     * @param bundleName bundle名称
     * @param path 资源路径
     * @param assetType 资源类型
     * @param onProgress 加载进度回调
     * @param onComplete 加载完成回调
     */
    loadAsset(bundleName: string, path: string, assetType: any, onProgress?: Function, onComplete?: Function) {
        let bundle = assetManager.getBundle(bundleName);
        if (bundle && bundle.get(path, assetType)) {
            if (onComplete) {
                onComplete(null, bundle.get(path, assetType));
            }
            return;
        }

        let loadAssetFunc = () => {
            bundle.load(path, assetType, (finish: number, total: number) => {
                if (onProgress) {
                    onProgress(finish, total);
                }
            }, (err, asset) => {
                if (err) {
                    tyqSDK.log("ResManager.loadAsset error:" + err.message, bundleName, path, err);
                    if (onComplete) {
                        onComplete(err);
                    }
                    return;
                }
                if (onComplete) {
                    onComplete(null, asset);
                }
            });
        };

        if (!bundle) {
            assetManager.loadBundle(bundleName, (err, retBundle) => {
                if (err) {
                    if (onComplete) {
                        onComplete(err);
                    }
                    return;
                }
                bundle = retBundle;
                loadAssetFunc();
            });
            return;
        }

        loadAssetFunc();
    }
}

export const tyqResManager = TyqResManager.instance;

